package com.itheima.es;

import com.alibaba.fastjson.JSON;
import com.itheima.es.pojo.User;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.Avg;
import org.elasticsearch.search.aggregations.metrics.AvgAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 演示: 操作es客户端
        聚合处理
 *
 * @作者 itcast
 * @创建日期 2021/3/19 9:09
 **/
public class EsDemo06 {
    RestHighLevelClient client;
    /**
     * 按照性别分组
     * 求每个小组的平均年龄
     * @throws IOException
     */
    @Test
    public void aggregations() throws IOException {
        //1. 创建搜索请求
        SearchRequest request = new SearchRequest("user");
        //2.
        SearchSourceBuilder builder = new SearchSourceBuilder();
        // 创建了按照性别分组的聚合条件
        TermsAggregationBuilder termGender = AggregationBuilders.terms("term_by_gender").field("gender");
        // 创建按照年龄求平均值的聚合条件
        AvgAggregationBuilder avgAge = AggregationBuilders.avg("avg_by_age").field("age");
        // 将平均年龄设置成分组后的子聚合处理
        termGender.subAggregation(avgAge);
        builder.aggregation(termGender);
        request.source(builder);
        //3.执行请求
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        // 得到总聚合结果
        Aggregations aggregations = response.getAggregations();
        // 得到分桶的聚合结果
        Terms termResult = aggregations.get("term_by_gender");
        // 遍历分桶结果集合
        List<? extends Terms.Bucket> buckets = termResult.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            System.out.println("当前分组名key:" + bucket.getKey());
            System.out.println("当前分组人数:" + bucket.getDocCount());
            // 获取当前分桶下子聚合的结果
            Aggregations subAggs = bucket.getAggregations();
            Avg avgResult = subAggs.get("avg_by_age");
            System.out.println("当前分组的平均年龄: " + avgResult.getValue());
        }
    }

    @Before
    public void init(){
        // 创建操作es的客户端
        client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("192.168.200.129",9200,"http")
                )
        );
    }
    @After
    public void close(){
        try {
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

//    public static void main(String[] args) {
//        // 创建操作es的客户端
//        RestHighLevelClient client = new RestHighLevelClient(
//                RestClient.builder(
//                        new HttpHost("192.168.200.129",9200,"http")
//                )
//        );
//        // 使用client操作es
//
//        // 使用完毕后需要释放链接
//        try {
//            client.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }


}
